﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace Adams.Admin.DataAccess.Pages
{
    public static class Create
    {
        public static Adams.Admin.DataTransfer.Pages.Create.PageLoad PageLoad(int id)
        {
            var data = new Adams.Admin.DataTransfer.Pages.Create.PageLoad();
            data.Page = new Shared.Entities.Pages.Page();

            if (id > 0)
            {
                using (SqlDataReader dr = DB.RunDataReader(@"
SELECT * FROM Pages.Pages WHERE PageID = @PageID
", CommandType.Text,
                DB.CreateParameter("@PageID", id, SqlDbType.Int)))
                {
                    dr.Read();
                    data.Page.ID = dr["PageID"].DbInt();
                    data.Page.Title = dr["Title"].DbString();
                    data.Page.Url = dr["Url"].DbString();
                    data.Page.Content = dr["Content"].DbString();
                }
            }

            return data;
        }

        public static void Save(DataTransfer.Pages.Create.FormInput input)
        {
            DB.Run(@"
IF(@PageID > 0)
BEGIN
    UPDATE Pages.Pages SET
        Title = @Title
        ,Url = @Url
        ,Content = @Content
    WHERE PageID = @PageID
END
ELSE
BEGIN
    INSERT INTO Pages.Pages (
        Title
        ,Url
        ,Content)
    VALUES (
        @Title
        ,@Url
        ,@Content)
END
    ", CommandType.Text,
                    DB.CreateParameter("@PageID", input.ID.ToInt()),
                    DB.CreateParameter("@Title", input.Title.ToNString()),
                    DB.CreateParameter("@Url", input.Url.ToNString()),
                    DB.CreateParameter("@Content", input.Content.ToNString()));
        }

        public static Adams.Admin.DataTransfer.Pages.Create.PageInfo GetPageInfo(string url, int pageId)
        {
            var data = new Adams.Admin.DataTransfer.Pages.Create.PageInfo();

            using (SqlDataReader dr = DB.RunDataReader(@"
IF (@PageID > 0)
BEGIN
    SELECT Url
    FROM Pages.Pages
    WHERE PageID = @PageID
END

SELECT COUNT(*) AS Count
FROM Pages.Pages
WHERE Url = @Url
", CommandType.Text,
                DB.CreateParameter("@PageID", pageId),
                DB.CreateParameter("@Url", url)))
            {
                if (pageId > 0)
                {
                    dr.Read();
                    data.Url = dr["Url"].DbString();
                    dr.NextResult();
                }
                dr.Read();
                data.Exists = dr["Count"].DbInt() > 0;
            }

            return data;
        }
    }
}
